from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import Required, Length, EqualTo, Email
from wtforms.validators import ValidationError

from app.models import User

# 注册表单
class RegisterForm(FlaskForm):
    username = StringField("用户名", validators=[Required(), Length(1, 64, "最小长度为1 最大长度为64")])
    email = StringField("邮箱", validators=[Required(), Email("不是合法的邮箱")])
    password = PasswordField("密码", validators=[Required(), Length(8, 64, "最小长度为8 最大长度为64")])
    confirm = PasswordField("确认密码", validators=[Required(), EqualTo("password", "密码不一致")])
    submit = SubmitField("注册")

    # 自定义验证函数
    def validate_username(self, field):
        username = field.data
        if User.query.filter_by(username=username, deleted="false").first():
            raise ValidationError("该用户名已经被注册了呢, 重新换一个吧~")

    def validate_email(self, field):
        email = field.data
        if User.query.filter_by(email=email, deleted="false").first():
            raise ValidationError("该邮箱已经被注册了呢, 可以直接登录呀~")

# 登录表单
class LoginForm(FlaskForm):
    email = StringField("邮箱", validators=[Required(), Email("不是合法的邮箱")])
    password = PasswordField("密码", validators=[Required(), Length(6, 64, "最小长度为6 最大长度为64")])
    remember = BooleanField("记住密码")
    submit = SubmitField("登录")

# 重置密码请求表单
class ResetPasswordRequestForm(FlaskForm):
    email = StringField("您的邮箱", validators=[Required(), Email("不是合法的邮箱")]) 
    submit = SubmitField("发送")

# 重置密码表单
class ResetPasswordForm(FlaskForm):
    password = PasswordField("新密码", validators=[Required(), Length(6, 64, "最小长度为6 最大长度为64")])
    confirm = PasswordField("确认密码", validators=[Required(), EqualTo("password", "密码不一致")])
    submit = SubmitField("修改")